package com.common;
import com.common.MyCaptchaRender;
import com.common.util.email.EmailTool;
import com.jfinal.core.Controller;
import com.model.Section;
import com.model.User;

public class CommonController extends Controller {
	//生成验证码
	public void captcha() {
		render(new MyCaptchaRender(60, 22, 4, true));
	}
	
	public void emailCaptcha(){
		String email = getPara("email");
		User checkUser = User.dao.findFirst("select * from user where email=?", email);
		if (checkUser != null && checkUser.getId() != null) {
			setAttr("err", "此邮箱已被使用,请重新填写");
		}else{
			String emailCaptcha = randomCount(6);
			if(email!=null&&!"".equals(email.trim())){
				getSession().setAttribute("emailCaptcha", emailCaptcha);
				EmailTool.sendMian(email, "邮件验证码", "邮件验证码是："+emailCaptcha+"");
				setAttr("err", "发送成功,请查收邮件（注意验证码邮件可能会被邮箱识别成垃圾邮件，注意查收）！");
			}else{
				setAttr("err", "发送失败！");
			}
		}
		renderJson();
	}
	
	/**
	 * 随机产生count位字符串
	 * @param count
	 * @return
	 */
	private String randomCount(int count) {
        String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[count]; 
        for (int i = 0; i < rands.length; i++) 
        { 
            int rand = (int) (Math.random() * a.length()); 
            rands[i] = a.charAt(rand); 
        } 
        String emailCaptcha = "";
        for(int i=0;i<rands.length;i++){
        	emailCaptcha = emailCaptcha +rands[i];
        }
        return emailCaptcha.trim();
    }
	
	/**
	 * 校验验证码是否正确
	 */
	public void checkVCode(){
		String captcha = getPara("captcha");
		boolean vCodeCheck = MyCaptchaRender.validate(this, captcha);
		renderJson();
		if (vCodeCheck) {
			setAttr("valid", true);
		}else{
			setAttr("valid", false);
		}
	}
	
	
	/**
	 * 检查用户名是否存在,前台ajax验证
	 */
	public void checkUserName(){
		String userName = getPara("userName");
		User checkUser =User.dao.findFirst("select * from user where user_name=?",userName);
		renderJson();
		if (checkUser != null && checkUser.getId() != null) {
			setAttr("valid", false);
		}else{
			setAttr("valid", true);
		}
	}
	
	/**
	 * 校验标题是否可以使用
	 */
	public void checkSectionName(){
		String name = getPara("name");
		Section checkSection =Section.dao.findFirst("select * from section where name=?",name);
		renderJson();
		if (checkSection != null && checkSection.getId() != null) {
			setAttr("valid", false);
		}else{
			setAttr("valid", true);
		}
	}
	
	
}
